package api

import (
	"lutai/src/bll"
	"lutai/src/logger"
	"lutai/src/model"
	"lutai/src/schema"
	"net/http"

	"github.com/teambition/gear"
)

// Test API接口
type Test struct {
	models  *model.All
	testBll *bll.Test
}

// Init 初始化服务配置
func (a *Test) Init(blls *bll.All) *Test {
	a.models = blls.Models
	a.testBll = blls.Test
	return a
}

// Query /test
func (a *Test) Query(ctx *gear.Context) (err error) {
	tests, err := a.testBll.Query()
	if err != nil {
		logger.Errorf("Query Error:%s", err.Error())
		return gear.ErrInternalServerError
	}

	return ctx.JSON(http.StatusOK, tests)
}

// Get /test/:id
func (a *Test) Get(ctx *gear.Context) (err error) {
	id := ctx.Param("id")
	test, err := a.testBll.Get(id)
	if err != nil {
		logger.Errorf("Get Error:%s", err.Error())
		return gear.ErrInternalServerError.WithMsg("没有找到数据")
	}

	return ctx.JSON(http.StatusOK, test)
}

// Create /test
func (a *Test) Create(ctx *gear.Context) (err error) {
	test := new(schema.Test)

	if verr := ctx.ParseBody(test); verr != nil {
		return gear.ErrBadRequest.From(verr)
	}
	err = a.testBll.Create(test)
	if err != nil {
		logger.Errorf("Create Error:%s", err.Error())
		return gear.ErrInternalServerError
	}

	return ctx.JSON(http.StatusOK, test)
}

// Update /test/:id
func (a *Test) Update(ctx *gear.Context) (err error) {
	test := new(schema.Test)

	if verr := ctx.ParseBody(test); verr != nil {
		return gear.ErrBadRequest.From(verr)
	}

	test.RecordID = ctx.Param("id")
	err = a.testBll.Update(test)
	if err != nil {
		logger.Errorf("Update Error:%s", err.Error())
		return gear.ErrInternalServerError
	}

	return ctx.JSON(http.StatusOK, "更新成功")
}

// Delete /test/:id
func (a *Test) Delete(ctx *gear.Context) (err error) {
	id := ctx.Param("id")
	err = a.testBll.Delete(id)
	if err != nil {
		logger.Errorf("Delete Error:%s", err.Error())
		return gear.ErrInternalServerError
	}

	return ctx.JSON(http.StatusOK, "删除成功")
}
